class List {
    constructor() {
        this.contentBox = document.querySelector('.list')
        this.cateBox = document.querySelector('.cateBox>ul')
        this.filterBox = document.querySelector('.filterBox')
        this.searchBox = document.querySelector('.searchBox>input')
        this.prev = document.querySelector('#prev')
        this.next = document.querySelector('#next')
        this.total = document.querySelector('.total')
        this.sele = document.querySelector('.pagination>select')
        this.totalNum = 0
        this.box1 = document.getElementById('box1')

        this.searchParams = {
            current: 1,
            page: 1,
            pagesize: 24,
            search: '',
            filter: '',
            saleType: 10,
            sortType: 'id',
            sortMethod: 'ASC',
            category: '' // 分类
        }
        this.dataList = []
        this.init()
        //swiper轮播

    }
    init() {
        this.showList1()
        this.showList()
        // this.showCate()
        this.handleList()
        this.handleSearch()
        this.handleSelect()
        this.handleClick()
        this.handleAdd()
        this.handleCir()
    }
    async handleCir() {
        let params = {
            url: "/banner/list1",
        }
        let res = await axios.get(params)
        // console.log(res);
        let arr = res.list.slice(1, 6)
        let str = ''
        arr.forEach(it => {
            str += `<div class="swiper-slide"><img src="${it.imgurl}" class="img1"></div>`
        })
        this.box1.innerHTML = str

    }
    // 分页点击事件 
    handleClick() {
        this.next.onclick = () => {
            if (this.searchParams.current == this.totalNum) {
                return
            }
            this.searchParams.current++
            this.showList()
        }

        this.prev.onclick = () => {
            if (this.searchParams.current == 1) {
                return
            }
            this.searchParams.current--
            this.showList()
        }
    }
    // 改变上下按钮的样式
    changeDisable() {
        if (this.searchParams.current == 1) {
            this.prev.classList.add('disable')
        }
        if (this.searchParams.current == this.totalNum) {
            this.next.classList.add('disable')
        }
        if (this.searchParams.current > 1 && this.searchParams.current < this.totalNum) {
            this.next.classList.remove('disable')
            this.prev.classList.remove('disable')
        }
    }
    // 下拉选择数量
    handleSelect() {
        this.sele.onchange = () => {
            this.searchParams.pagesize = this.sele.value
            this.showList()
        }
    }
    // 模糊搜索 
    handleSearch() {
        let that = this
        this.searchBox.oninput = (function () {
            let timer = null
            return () => {
                clearTimeout(timer)
                timer = setTimeout(() => {
                    that.searchParams.search = that.searchBox.value
                    that.showList1()
                    that.showList()
                }, 500);
            }
        })()
    }
    // 列表筛选
    handleList() {
        this.filterBox.onclick = (e) => {
            var e = e || window.event
            var target = e.target || e.srcElement
            // 分类
            if (target.className == 'cateItem') {
                this.changeActive(target)
                this.searchParams.category = target.innerText == '全部' ? '' : target.innerText
                this.showList()
            }
            // 筛选 
            if (target.className == 'saleItem') {
                console.log(target)
                this.changeActive(target)
                this.searchParams.filter = target.dataset.sale
                this.showList()
            }
            //折扣
            if (target.className == 'numberItem') {
                this.changeActive(target);
                this.searchParams.saleType = target.dataset.number;
                this.showList();
            }

            //排序
            if (target.className == 'sortItem') {
                this.changeActive(target);
                this.searchParams.sortType = target.dataset.type;
                this.searchParams.sortMethod = target.dataset.method;
                this.showList();
            }


        }
    }
    changeActive(ele) {
        [...ele.parentNode.children].forEach(it => {
            it.classList.remove('active')
        })
        ele.classList.add('active')
    }
    // 分类渲染 
    /*  showCate() {
         let params = {
             url: '/goods/category'
         }
         axios.get(params).then(res => {
             console.log(res)
             if (res.code == 1) {
                 //   let str = `<li class='cateItem active'>全部</li>`
                 //       res.list.forEach(item=>{
                 //           str +=`<li class='cateItem'>${item}</li>`
                 //       })
                 //       this.cateBox.innerHTML = str
 
                 let str = res.list.reduce((result, item) => {
                     result += `<li class='cateItem'>${item}</li>`
                     return result
                 }, `<li class='cateItem active'>全部</li>`)
 
                 this.cateBox.innerHTML = str
             }
         })
     } */
    //
    // 商品列表渲染
    /* async showList() {
        let params = {
            url: "/goods/list",
            query: this.searchParams
        }
        let res = await axios.get(params)
        console.log(res)
        if (res.code == 1) {

            this.dataList = res.list
            this.totalNum = res.total
            this.changeDisable()
            this.total.innerHTML = `${this.searchParams.current}/${res.total}`
            // console.log(this.dataList)
            let str = ''
            this.dataList.forEach((item, index) => {
                str += `
                   <li data-goods_id=${item.goods_id}>
                    <div class="show" >
                        <img src="${item.img_big_logo}" alt="">
                        ${item.is_hot ? '<span class="hot">热销</span>' : ''}
                        ${item.is_sale ? '<span class="sale">折扣</span>' : ''}
                    </div> 
                    <p class="title">${item.title}</p>
                    <p class="price">
                        <span class="current">￥ ${item.current_price}</span>
                        <span class="origin">￥ ${item.price}</span>
                    </p>
                    <button data-goods_id=${item.goods_id}>加入购物车</button>
                    </li>
                 `
            })

            this.contentBox.innerHTML = str
        }

    } */
    //预渲染
    async showList1() {
        let params = {
            url: "/good/list",
            query: this.searchParams
        }
        let res = await axios.get(params)
        console.log(res)
        if (res.code == 1) {
            this.dataList = res.list
            this.totalNum = res.total
            this.changeDisable()
            this.total.innerHTML = `${this.searchParams.current}/${res.total}`
            console.log(this.dataList)
            let str = ''
            this.dataList.forEach((item, index) => {
                str += `
                   <li data-goods_id=${item.goods_id}>
                    <div class="show" >
                        <img src="${item.imgurl}" alt="">
                        ${item.is_hot ? '<span class="hot">热销</span>' : ''}
                        ${item.is_sale ? '<span class="sale">折扣</span>' : ''}
                    </div> 
                    <p class="title">${item.goodname}</p>
                    <p class="price">
                        <span class="origin">￥ ${item.price}</span>
                    </p>
                    <button data-goods_id=${item.goods_id}>加入购物车</button>
                    </li>
                 `
            })

            this.contentBox.innerHTML = str
        }

    }
    //排序渲染
    async showList() {
        let params = {
            url: "/good/price",
            query: this.searchParams
        }
        let res = await axios.get(params)
        console.log(res)
        if (res.code == 1) {
            this.dataList = res.list
            this.totalNum = res.total
            this.changeDisable()
            this.total.innerHTML = `${this.searchParams.current}/${res.total}`
            console.log(this.dataList)
            let str = ''
            this.dataList.forEach((item, index) => {
                str += `
                   <li data-goods_id=${item.goods_id}>
                    <div class="show" >
                        <img src="${item.imgurl}" alt="">
                        ${item.is_hot ? '<span class="hot">热销</span>' : ''}
                        ${item.is_sale ? '<span class="sale">折扣</span>' : ''}
                    </div> 
                    <p class="title">${item.goodname}</p>
                    <p class="price">
                        <span class="origin">￥ ${item.price}</span>
                    </p>
                    <button data-goods_id=${item.goods_id}>加入购物车</button>
                    </li>
                 `
            })

            this.contentBox.innerHTML = str
        }

    }
    // 点击加入购物车 和跳转到详情 
    handleAdd() {
        this.contentBox.onclick = async (e) => {
            var e = e || window.event
            var target = e.target || e.srcElement

            console.log(target)
            // 先判断是不是跳转详情
            if (target.nodeName == 'LI') {

                let goods_id = target.dataset.goods_id
                console.log(goods_id)

                sessionStorage.setItem('goods_id', goods_id)
                location.href = `../html/detail.html?goods_id=${goods_id}&name=liuxingjie`
            }

            // 判断加入购物车  
            if (target.nodeName == 'BUTTON') {
                // 判断登录了没有  
                if (cookie.getItem('token')) {
                    // 发送请求 加入购物车 
                    let params = {
                        url: '/cart/add',
                        query: {
                            id: cookie.getItem('userId'),
                            goodsId: target.dataset.goods_id
                        }
                    }
                    let res = await axios.post(params)
                    console.log(res)
                    if (res.code == 1) {
                        alert(res.message)
                    }
                } else {
                    // 提醒登录 
                    alert('你还没有登录！请登录以后再操作！')
                    location.href = '../html/login.html'
                }
            }
        }
    }
}

new List()